package com.leji.song.mainPage;

import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.*;
import com.dgl.sdk.util.DBStore;
import com.dgl.sdk.util.SharePreStore;
import com.dgl.sdk.util.TimeHelp;
import com.google.gson.Gson;
import com.leji.song.R;
import com.leji.song.extra.BaseActivity;
import com.leji.song.extra.BaseCoreActivity;
import com.leji.song.httpInterface.BaseAjaxParams;
import com.leji.song.httpInterface.HttpInterface;
import com.leji.song.httpInterface.NomalResult;
import com.leji.song.mainPage.model.DS_Goods;
import com.leji.song.mainPage.model.DS_GoodsOrder;
import com.leji.song.mainPage.model.DS_TranslatePrice;
import com.leji.song.mine.AdressManagerActivity;
import com.leji.song.mine.model.DS_Address;
import com.leji.song.util.ConstAns;
import com.leji.song.util.DateTimePickerDialog;
import com.leji.song.util.MyAjaxCallBack;
import net.tsz.afinal.FinalHttp;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by colin.ding on 2014/6/17.
 */
public class SubmitOrderActivity extends BaseActivity{

    private ListView orderListView;
    private List<DS_Goods> orderList = new ArrayList<DS_Goods>();
    private TextView translatePriceInfo, money;
    private float totalMoney = 0.0f;
    private TextView name, phone, address;

    private TextView setAddress;
    private View myAdress;

    private Button submit;

    private String sendTime;
    private EditText extra;
    List<DS_TranslatePrice> tPriceList = new ArrayList<DS_TranslatePrice>();

    boolean isHaveAddress = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setAnimType(RIGHT_ENTER_LEFT_EXT);
        super.onCreate(savedInstanceState);

        orderList = (List<DS_Goods>)getIntent().getSerializableExtra("orderList");
        tPriceList = (List<DS_TranslatePrice>)getIntent().getSerializableExtra("translatePrice");

        setContentView(R.layout.takeaway_order);
        initView();
        getAddress();

        showTotalPrice(orderList);
    }

    private void getAddress() {


        String choosedAddressID = SharePreStore.readString(ConstAns.CHOOSED_ADDRESS_ID);
        List<DS_Address>  addressList = DBStore.readAll(DS_Address.class, ConstAns.DB_TABLE_MY_ADDRESS);
        if((addressList!= null) &&(addressList.size()>0)){
            for(DS_Address addressData:addressList){
                if(choosedAddressID.equals(addressData.getAddressID())){
                    name.setText(addressData.getName());
                    phone.setText(addressData.getPhoneNum());
                    address.setText(addressData.getAdress());

                    isHaveAddress = true;
                    break;
                }
            }
        }

        if(isHaveAddress){
            setAddress.setVisibility(View.GONE);
            myAdress.setVisibility(View.VISIBLE);

            myAdress.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SubmitOrderActivity.this, AdressManagerActivity.class);
                    startActivityForResult(intent, 0);
                }
            });

        }else{
            setAddress.setVisibility(View.VISIBLE);
            myAdress.setVisibility(View.GONE);

            setAddress.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(SubmitOrderActivity.this, AdressManagerActivity.class);
                    startActivityForResult(intent, 0);
                }
            });
        }

    }

    private void initView() {
        setActivityTitle("外卖订单");
        setReturnBtn();

        orderListView = (ListView) findViewById(R.id.orderListView);
        translatePriceInfo = (TextView) findViewById(R.id.translatePriceInfo);
        money = (TextView) findViewById(R.id.money);
        name = (TextView) findViewById(R.id.name);
        phone = (TextView) findViewById(R.id.phone);
        address = (TextView) findViewById(R.id.address);

        setAddress = (TextView) findViewById(R.id.setAddress);
        myAdress = (View) findViewById(R.id.myAdress);
        extra = (EditText) findViewById(R.id.extra);

        submit = (Button) findViewById(R.id.submit);

        GoodsAdapter adapter = new GoodsAdapter(this, orderList, new GoodsAdapter.BuyGoodsCallback() {
            @Override
            public void onClick(DS_Goods goods) {
                calcBuyGoodsResult(goods);
            }
        });
        orderListView.setAdapter(adapter);

        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePickerDialog2();
            }
        });

    }

    public void showTimePickerDialog() {
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis(System.currentTimeMillis());
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        TimePickerDialog dialog = new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {

            @Override
            public void onTimeSet(TimePicker arg0, int hour, int minute) {
                System.out.println(hour + ":" + minute);

                sendTime = hour + ":" + minute;
                submitOrder();

            }

        }, hour, minute, true);

        dialog.setTitle("选择外送时间");
        dialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        dialog.show();
    }

    public void showTimePickerDialog2() {
        DateTimePickerDialog dateTimePicKDialog = new DateTimePickerDialog(
                this);
        dateTimePicKDialog.dateTimePicKDialog(new DateTimePickerDialog.GetTimeCallback() {
            @Override
            public void onGetTime(String time) {
                sendTime = time;
                submitOrder();
            }
        }, 3);
    }

    private void submitOrder() {

        if((orderList== null) || (orderList.size()==0)){
            showToast("没有订单可提交");
            return;
        }

        if(!isHaveAddress){
            showToast("请设置收货地址");
            return;
        }
        List<DS_GoodsOrder> goodsOrdersList = new ArrayList<DS_GoodsOrder>();
        for(DS_Goods goods: orderList){
            DS_GoodsOrder goodsOrder = new DS_GoodsOrder();
            goodsOrder.setId(goods.getId());
            goodsOrder.setAmount(Integer.toString(goods.getBuyNum()));

            goodsOrdersList.add(goodsOrder);
        }

        //菜的订单
        if(getIntent().getStringExtra("fromWho").equals("food")){
            BaseAjaxParams params = new BaseAjaxParams();
            params.put(HttpInterface.HIF_SubmitFoodOrder.params.memberid, SharePreStore.readString(ConstAns.MY_ID));
            params.put(HttpInterface.HIF_SubmitFoodOrder.params.shopsId, getIntent().getStringExtra("shopID"));
            params.put(HttpInterface.HIF_SubmitFoodOrder.params.time, TimeHelp.geTime("yyyy-MM-dd HH:mm:ss"));
            params.put(HttpInterface.HIF_SubmitFoodOrder.params.address, address.getText().toString());
            params.put(HttpInterface.HIF_SubmitFruitOrder.params.username, name.getText().toString());
            params.put(HttpInterface.HIF_SubmitFruitOrder.params.phone, phone.getText().toString());
            params.put(HttpInterface.HIF_SubmitFoodOrder.params.gettotime, sendTime);
            Gson gson = new Gson();
            params.put(HttpInterface.HIF_SubmitFoodOrder.params.goods, gson.toJson(goodsOrdersList));



            FinalHttp fh = new FinalHttp();
            fh.get(HttpInterface.HIF_SubmitFoodOrder.address, params, new MyAjaxCallBack<Object>((BaseCoreActivity)this) {
                @Override
                public void onSuccess(Object o) {
                    super.onSuccess(o);

                    if(NomalResult.isNormalResult(o, SubmitOrderActivity.this)){
                        SubmitOrderSucceedDialog dialog = new SubmitOrderSucceedDialog(SubmitOrderActivity.this);
                        dialog.show();
                    }

                }
            });
        }else{    //水果订单

            BaseAjaxParams params = new BaseAjaxParams();
            params.put(HttpInterface.HIF_SubmitFruitOrder.params.memberid, SharePreStore.readString(ConstAns.MY_ID));
            params.put(HttpInterface.HIF_SubmitFruitOrder.params.time, TimeHelp.geTime("yyyy-MM-dd HH:mm:ss"));
            params.put(HttpInterface.HIF_SubmitFruitOrder.params.address, address.getText().toString());
            params.put(HttpInterface.HIF_SubmitFruitOrder.params.gettotime, sendTime);
            params.put(HttpInterface.HIF_SubmitFruitOrder.params.username, name.getText().toString());
            params.put(HttpInterface.HIF_SubmitFruitOrder.params.phone, phone.getText().toString());
            Gson gson = new Gson();
            params.put(HttpInterface.HIF_SubmitFruitOrder.params.goods, gson.toJson(goodsOrdersList));



            FinalHttp fh = new FinalHttp();
            fh.get(HttpInterface.HIF_SubmitFruitOrder.address, params, new MyAjaxCallBack<Object>((BaseCoreActivity)this) {
                @Override
                public void onSuccess(Object o) {
                    super.onSuccess(o);

                    if(NomalResult.isNormalResult(o, SubmitOrderActivity.this)){
                        SubmitOrderSucceedDialog dialog = new SubmitOrderSucceedDialog(SubmitOrderActivity.this);
                        dialog.show();
                    }

                }
            });
        }
    }


    private void calcBuyGoodsResult(DS_Goods goods) {

        boolean isHave =false;
        for(DS_Goods goods1: orderList){

            if(goods1.getId() == goods.getId()){
                goods1.setBuyNum(goods.getBuyNum());
                isHave = true;
                break;
            }
        }

        if(!isHave){
            orderList.add(goods);
        }

        showTotalPrice(orderList);
    }

    private void showTotalPrice(List<DS_Goods> buyGoodsResultList) {
        totalMoney = 0;
        for(DS_Goods goods: buyGoodsResultList){
            totalMoney += goods.getBuyNum()*Float.valueOf(goods.getPrice());
        }

        for(DS_TranslatePrice price:tPriceList){
            if(totalMoney < Float.valueOf(price.getS_price())){

                float translatePrice = 0;
                try{
                    translatePrice = Float.valueOf(price.getP_price());
                    totalMoney += translatePrice;
                }catch (Exception e){
                    e.printStackTrace();
                }

                money.setText(Float.toString(totalMoney));

                translatePriceInfo.setText("包含运费"+price.getP_price()+"元");
                break;
            }
        }

//        if(totalMoney<50.0f){
//            translatePriceInfo.setText("运费10元，还差"+(Float.toString(50.0f-totalMoney))+ "元5元运费");
//        }else if(totalMoney < 100.0f){
//            translatePriceInfo.setText("运费5元，还差"+(Float.toString(100.0f-totalMoney))+ "元免运费");
//        }else {
//            translatePriceInfo.setText("免运费");
//        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        getAddress();
    }
}
